<template>
  <sub-page class="lower-level-page">
    <title-header :title="currentView === 'list' ? '下级列表' : '下级点数风暴'" />

    <main-card>
      <!-- 下级列表视图 -->
      <div v-if="currentView === 'list'">
        <div class="table-tools">
          <el-button
            type="primary"
            size="small"
            :loading="isRefreshing"
            :disabled="isRefreshing || !hasPermission"
            @click="fetchList"
          >
            刷新列表
          </el-button>
        </div>
        <my-table class="table-container">
          <el-table
            :data="hasPermission ? tableData : []"
            style="width: 100%"
            header-row-class-name="table-header"
            v-loading="isRefreshing"
            element-loading-text="加载中..."
          >
            <el-table-column type="index" label="编号" width="80" align="center" header-align="center" />
            <el-table-column prop="theme" label="酒吧名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="emcee_name" label="主持人名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="phonenumber" label="手机号" min-width="160" show-overflow-tooltip />
            <el-table-column label="操作" width="180" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="toPointStorm(scope.row)" :disabled="!scope.row.id">
                  点数风暴明细
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </my-table>
        <div class="pageNation-container" v-if="hasPermission">
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalResult"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
        <div class="no-permission" v-else>
          您暂无查看下级列表的权限。
        </div>
      </div>

      <!-- 点数风暴二级视图 -->
      <div v-else-if="currentView === 'pointStorm'">
        <div class="back-tools">
          <el-button size="small" @click="backToList">
            <i class="el-icon-arrow-left"></i> 返回下级列表
          </el-button>
          <div class="bar-name" v-if="selectedTheme">{{ selectedTheme }}</div>
          <el-button
            size="small"
            type="primary"
            :loading="isStormRefreshing"
            :disabled="isStormRefreshing"
            @click="fetchStormList"
          >
            刷新列表
          </el-button>
        </div>

        <my-table class="table-container">
          <el-table
            :data="stormTableData"
            style="width: 100%"
            header-row-class-name="table-header"
            v-loading="isStormRefreshing"
            element-loading-text="加载中..."
          >
            <el-table-column type="index" label="编号" width="80" align="center" header-align="center" />
            <el-table-column prop="start_time" label="开始时间" min-width="160" align="center" header-align="center" />
            <el-table-column prop="end_time" label="结束时间" min-width="160" align="center" header-align="center" />
            <el-table-column label="游戏时长" min-width="120" align="center" header-align="center">
              <template slot-scope="scope">
                <span>
                  {{ scope.row._pointJson && scope.row._pointJson.gameTime ? `${scope.row._pointJson.gameTime} min` : '-' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="单次价格" min-width="120" align="center" header-align="center">
              <template slot-scope="scope">
                <span>{{ (scope.row._pointJson && scope.row._pointJson.perPrice) || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="奖品信息" min-width="260" align="center" header-align="center">
              <template slot-scope="scope">
                <div
                  v-if="scope.row._pointJson && scope.row._pointJson.awardData && scope.row._pointJson.awardData.length"
                  class="award-list"
                >
                  <div class="award-item" v-for="(aw, idx) in scope.row._pointJson.awardData" :key="idx">
                    <img v-if="aw.prizeImg" :src="aw.prizeImg" width="47" height="31" @error="onPrizeImgError" />
                    <span class="award-name">{{ aw.prizeName || '-' }}</span>
                  </div>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="140" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="openStormDetail(scope.row)">查看明细</el-button>
              </template>
            </el-table-column>
          </el-table>
        </my-table>

        <div class="pageNation-container">
          <el-pagination
            background
            :current-page="stormCurrentPage"
            :page-size="stormPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="stormTotalResult"
            @current-change="handleStormCurrentChange"
            @size-change="handleStormSizeChange"
          />
        </div>
      </div>
    </main-card>

    <!-- 点数风暴单局详情弹窗 -->
    <storm-detail-dialog
      :visible.sync="stormDetailVisible"
      :live-id="selectedLiveId"
      :dice-id="selectedDiceId"
    />
  </sub-page>
</template>

<script>
import SubPage from '@/components/subPage';
import TitleHeader from '@/layout/home/components/header/titleHeader';
import MainCard from '@/components/mainCard';
import MyTable from '@/components/myTable';
import { getLowerLevelList } from '@/api/app/invite';
import { getPointDiceList } from '@/api/setting/activityIncome/activityIncomeData';
import StormDetailDialog from './components/StormDetailDialog';

export default {
  name: 'LowerLevelList',

  components: { SubPage, TitleHeader, MainCard, MyTable, StormDetailDialog },

  data() {
    return {
      currentView: 'list', // 'list' 或 'pointStorm'

      // 下级列表数据
      tableData: [],
      isRefreshing: false,
      currentPage: 1,
      pageSize: 10,
      totalResult: 0,

      // 点数风暴数据
      selectedLiveId: '',
      selectedTheme: '',
      stormTableData: [],
      isStormRefreshing: false,
      stormCurrentPage: 1,
      stormPageSize: 10,
      stormTotalResult: 0,

      // 点数风暴详情弹窗
      stormDetailVisible: false,
      selectedDiceId: '',
    };
  },

  computed: {
    hasPermission() {
      const flag = this.$store.state.login.userInfo.isCanInviterPoint;
      return flag === '1';
    },
  },

  created() {
    if (this.hasPermission) {
      this.fetchList();
    }
  },

  methods: {
    fetchList() {
      if (!this.hasPermission || this.isRefreshing) return;
      this.isRefreshing = true;
      const params = {
        currentPage: `${this.currentPage}`,
        showCount: `${this.pageSize}`,
      };
      getLowerLevelList(params)
        .then((res) => {
          console.log(res);
          const data = res.data || {};
          this.tableData = data.varList || [];
          this.totalResult = data.totalResult || 0;
        })
        .catch(() => {
          this.tableData = [];
          this.totalResult = 0;
        })
        .finally(() => {
          this.isRefreshing = false;
        });
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchList();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchList();
    },

    toPointStorm(row) {
      if (!row.id) return;
      this.selectedLiveId = row.id;
      this.selectedTheme = row.theme || '';
      this.currentView = 'pointStorm';
      this.stormCurrentPage = 1;
      this.fetchStormList();
    },

    backToList() {
      this.currentView = 'list';
      this.selectedLiveId = '';
      this.selectedTheme = '';
      this.stormTableData = [];
      this.stormTotalResult = 0;
    },

    // 获取点数风暴列表
    fetchStormList() {
      if (this.isStormRefreshing) return;

      this.isStormRefreshing = true;
      const params = {
        splid: this.selectedLiveId,
        currentPage: `${this.stormCurrentPage}`,
        showCount: `${this.stormPageSize}`,
      };

      getPointDiceList(params)
        .then((res) => {
          const data = res.data || {};
          const list = (data.list || []).map((item) => {
            let pObj = null;
            if (item && item.pointJson) {
              try {
                pObj = typeof item.pointJson === 'string' ? JSON.parse(item.pointJson) : item.pointJson;
              } catch (e) {
                pObj = null;
              }
            }
            return { ...item, _pointJson: pObj };
          });
          this.stormTableData = list;
          this.stormTotalResult = data.totalResult || 0;
        })
        .catch(() => {
          this.stormTableData = [];
          this.stormTotalResult = 0;
        })
        .finally(() => {
          this.isStormRefreshing = false;
        });
    },

    handleStormCurrentChange(page) {
      this.stormCurrentPage = page;
      this.fetchStormList();
    },

    handleStormSizeChange(size) {
      this.stormPageSize = size;
      this.stormCurrentPage = 1;
      this.fetchStormList();
    },

    openStormDetail(row) {
      this.selectedDiceId = row.dice_id || '';
      this.stormDetailVisible = true;
    },

    onPrizeImgError(e) {
      e.target.style.display = 'none';
    },
  },
};
</script>

<style lang="less" scoped>
.lower-level-page {
  .table-tools {
    display: flex;
    align-items: center;
    padding: 20px 0 10px 20px;
  }
  .back-tools {
    display: flex;
    align-items: center;
    padding: 20px 0 10px 20px;
    gap: 12px;
    .bar-name {
      font-size: 14px;
      color: #303133;
    }
  }
  .table-container {
    margin-top: 10px;
  }
  .pageNation-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
  }
  .no-permission {
    text-align: center;
    padding: 40px 0;
    color: #909399;
  }
  .award-list {
    display: inline-flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px 16px;
  }
  .award-item {
    display: inline-flex;
    align-items: center;
    img {
      border-radius: 4px;
      margin-right: 6px;
    }
  }
  .award-name {
    max-width: 160px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
